#include "layoutstatemanager.h"
#include "systemconfig.h"
#include <QMutexLocker>
#include <QDebug>
// 静态成员初始化
LayoutStateManager* LayoutStateManager::s_instance = nullptr;
QMutex LayoutStateManager::s_mutex;
LayoutStateManager::LayoutStateManager(QObject *parent)
    : QObject(parent)
{
}
LayoutStateManager::~LayoutStateManager()
{
}
LayoutStateManager* LayoutStateManager::instance()
{
    // 双重检查锁定模式确保线程安全的单例
    if (s_instance == nullptr) {
        QMutexLocker locker(&s_mutex);
        if (s_instance == nullptr) {
            s_instance = new LayoutStateManager();
        }
    }
    return s_instance;
}
void LayoutStateManager::setFileLayoutMode(const QString& fileIdentity, LayoutMode mode)
{
    if (fileIdentity.isEmpty()) {
        return;
    }
    QMutexLocker locker(&m_stateMutex);
    // 检查是否需要更新
    LayoutMode currentMode = m_fileLayoutModes.value(fileIdentity, LayoutMode::SingleColumn);
    if (currentMode == mode) {
        return;
    }
    // 更新状态
    m_fileLayoutModes[fileIdentity] = mode;
    // 释放锁后发出信号，避免死锁
    locker.unlock();
    emitLayoutModeChanged(fileIdentity, mode);
}
LayoutMode LayoutStateManager::getFileLayoutMode(const QString& fileIdentity) const
{
    if (fileIdentity.isEmpty()) {
        return LayoutMode::SingleColumn;
    }
    QMutexLocker locker(&m_stateMutex);
    return m_fileLayoutModes.value(fileIdentity, LayoutMode::SingleColumn);
}
void LayoutStateManager::setBatchFileLayoutMode(const QStringList& fileIdentities, LayoutMode mode)
{
    if (fileIdentities.isEmpty()) {
        return;
    }
    QStringList changedFiles;
    {
        QMutexLocker locker(&m_stateMutex);
        for (const QString& fileIdentity : fileIdentities) {
            if (fileIdentity.isEmpty()) {
                continue;
            }
            LayoutMode currentMode = m_fileLayoutModes.value(fileIdentity, LayoutMode::SingleColumn);
            if (currentMode != mode) {
                m_fileLayoutModes[fileIdentity] = mode;
                changedFiles.append(fileIdentity);
            }
        }
    }
    // 发出批量变更信号
    if (!changedFiles.isEmpty()) {
        emit batchLayoutModeChanged(changedFiles, mode);
        // 为每个变更的文件发出单独的信号
        for (const QString& fileIdentity : changedFiles) {
            emitLayoutModeChanged(fileIdentity, mode);
        }
    }
}
int LayoutStateManager::calculateDisplayPages(const QString& fileIdentity, int basePageCount) const
{
    if (basePageCount <= 0) {
        return 1;
    }
    LayoutMode mode = getFileLayoutMode(fileIdentity);
    return calculateDisplayPages(mode, basePageCount);
}
int LayoutStateManager::calculateDisplayPages(LayoutMode mode, int basePageCount)
{
    if (basePageCount <= 0) {
        return 1;
    }
    switch (mode) {
        case LayoutMode::SingleColumn:
            // 1x1
            return basePageCount;
        case LayoutMode::TwoColumns:
            // 2x2 网格
            return (basePageCount + 4 - 1) / 4; // 向上取整除以4
        case LayoutMode::ThreeColumns:
            // 3x3 网格
            return (basePageCount + 9 - 1) / 9; // 向上取整除以9
        default:
            return basePageCount;
    }
}
void LayoutStateManager::setCurrentFile(const QString& fileIdentity)
{
    QMutexLocker locker(&m_stateMutex);
    if (m_currentFileIdentity == fileIdentity) {
        return; // 无变化
    }
    QString oldCurrentFile = m_currentFileIdentity;
    m_currentFileIdentity = fileIdentity;
    // 释放锁后发出信号
    locker.unlock();
    emit currentFileChanged(fileIdentity);
}
QString LayoutStateManager::getCurrentFile() const
{
    QMutexLocker locker(&m_stateMutex);
    return m_currentFileIdentity;
}
LayoutMode LayoutStateManager::getCurrentLayoutMode() const
{
    QMutexLocker locker(&m_stateMutex);
    if (m_currentFileIdentity.isEmpty()) {
        return LayoutMode::SingleColumn;
    }
    return m_fileLayoutModes.value(m_currentFileIdentity, LayoutMode::SingleColumn);
}
QString LayoutStateManager::getLayoutModeText(LayoutMode mode)
{
    switch (mode) {
        case LayoutMode::SingleColumn:
            return "单栏";
        case LayoutMode::TwoColumns:
            return "双栏";
        case LayoutMode::ThreeColumns:
            return "三栏";
        default:
            return "单栏";
    }
}
LayoutMode LayoutStateManager::convertFromOldLayoutMode(int oldLayoutMode)
{
    switch (oldLayoutMode) {
        case 1: return LayoutMode::SingleColumn;
        case 2: return LayoutMode::TwoColumns;
        case 3: return LayoutMode::ThreeColumns;
        default: return LayoutMode::SingleColumn;
    }
}
int LayoutStateManager::convertToOldLayoutMode(LayoutMode mode)
{
    switch (mode) {
        case LayoutMode::SingleColumn: return 1;
        case LayoutMode::TwoColumns: return 2;
        case LayoutMode::ThreeColumns: return 3;
        default: return 1;
    }
}
void LayoutStateManager::removeFileState(const QString& fileIdentity)
{
    if (fileIdentity.isEmpty()) {
        return;
    }
    QMutexLocker locker(&m_stateMutex);
    bool wasRemoved = m_fileLayoutModes.remove(fileIdentity) > 0;
    // 如果移除的是当前文件，清空当前文件
    if (m_currentFileIdentity == fileIdentity) {
        m_currentFileIdentity.clear();
        locker.unlock();
        emit currentFileChanged(QString());
    }
    if (wasRemoved) {
    }
}
void LayoutStateManager::clearAllStates()
{
    QMutexLocker locker(&m_stateMutex);
    int removedCount = m_fileLayoutModes.size();
    m_fileLayoutModes.clear();
    m_currentFileIdentity.clear();
    locker.unlock();
    emit currentFileChanged(QString());
    emit displayRefreshNeeded(); // 刷新所有显示
}
void LayoutStateManager::emitLayoutModeChanged(const QString& fileIdentity, LayoutMode mode)
{
    emit layoutModeChanged(fileIdentity, mode);
    // 如果是当前文件，还需要刷新显示
    {
        QMutexLocker locker(&m_stateMutex);
        if (m_currentFileIdentity == fileIdentity) {
            locker.unlock();
            emit displayRefreshNeeded(fileIdentity);
        } else {
        }
    }
}
// === 默认布局逻辑实现 ===
LayoutMode LayoutStateManager::getDefaultLayoutMode(const QString& filePath, int imageWidth, int imageHeight)
{
    // 1. 如果是PDF文件，默认单栏布局
    if (isPdfFile(filePath)) {
        return LayoutMode::SingleColumn;
    }
    // 2. 如果是图片文件且提供了尺寸信息
    if (imageWidth > 0 && imageHeight > 0) {
        if (isLongImage(imageWidth, imageHeight)) {
            return LayoutMode::TwoColumns;
        }
    }
    // 3. 其他情况（普通图片或未知类型），默认单栏布局
    return LayoutMode::SingleColumn;
}
bool LayoutStateManager::isPdfFile(const QString& filePath)
{
    return filePath.toLower().endsWith(".pdf");
}
bool LayoutStateManager::isLongImage(int imageWidth, int imageHeight)
{
    if (imageWidth <= 0 || imageHeight <= 0) {
        return false;
    }
    double aspectRatio = static_cast<double>(imageHeight) / imageWidth;
    bool isLong = aspectRatio > LONG_IMAGE_THRESHOLD;
    return isLong;
}
LayoutMode LayoutStateManager::getDefaultLayoutModeWithConfig(const QString& filePath,
                                                            const SystemConfig& systemConfig,
                                                            int imageWidth,
                                                            int imageHeight)
{
    // 1. PDF文件：使用配置中的PDF默认布局
    if (isPdfFile(filePath)) {
        return static_cast<LayoutMode>(systemConfig.pdfDefaultLayout);
    }
    // 2. 图片文件：根据配置和图片特征确定布局
    if (imageWidth > 0 && imageHeight > 0) {
        // 如果是长图片，使用配置中的图片默认布局
        if (isLongImage(imageWidth, imageHeight)) {
            return static_cast<LayoutMode>(systemConfig.imageDefaultLayout);
        }
    }
    // 3. 普通图片或未知类型：使用配置中的图片默认布局
    return static_cast<LayoutMode>(systemConfig.imageDefaultLayout);
}
